package SwingThread;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ExecutionException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.SwingWorker;

public class SwingThreadTest2 extends JFrame {
	private static final long serialVersionUID = 1L;
	private static final String STR = "Completed : ";
	private JProgressBar progressBar = new JProgressBar();
	private JTextField text = new JTextField(10);
	private JButton start = new JButton("Start");
	private JButton end = new JButton("End");
	private boolean flag = false;
	private int count = 0;
	Worker www = new Worker();

	public SwingThreadTest2() {
		this.setLayout(new FlowLayout());
		add(progressBar);
		text.setEditable(false);
		add(text);
		add(start);
		add(end);
		start.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				flag = true;
				System.out.println("start click");
				www.execute();
				   
			}
		});

		end.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				flag = false;
				 try {
						System.out.println(	www.get());
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (ExecutionException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				www.cancel(true);
			  
				www =null;
			}
		});

	}

	private void go() {
		while (count < 100) {
			try {
				Thread.sleep(100);// 这里比作要完成的某个耗时的工作
			} catch (InterruptedException e) {
				return;
			}
			// 更新进度条和输入框
			if (flag) {
				count++;
				progressBar.setValue(count);
				text.setText(STR + String.valueOf(count) + "%");
			} else {
				return;
			}
		}
	}

	private class Worker extends SwingWorker<String, String> {

		protected String doInBackground() throws Exception {
			go();
			return "end";
		}

	}

	public static void main(String[] args) {

		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					SwingThreadTest2 fg = new SwingThreadTest2();
					fg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
					fg.setSize(300, 100);
					Dimension screenSize = Toolkit.getDefaultToolkit()
							.getScreenSize();
					Dimension frameSize = fg.getSize();
					if (frameSize.height > screenSize.height)
						frameSize.height = screenSize.height;
					if (frameSize.width > screenSize.width)
						frameSize.width = screenSize.width;
					fg.setLocation((screenSize.width - frameSize.width) / 2,
							(screenSize.height - frameSize.height) / 2);

					fg.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

	}
}